package com.pan.kang.core;


import org.reflections.Reflections;
import org.springframework.stereotype.Component;

import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class DecoratorMapping {

    private DecoratorMapping() {
        init();
    }

    private final Map<Class<?>, Class<?>> MAPPING = new ConcurrentHashMap<Class<?>, Class<?>>(256);

    private void init() {
        // 路径固定
        new Reflections("com.pan.kang.demo.decoratorService")
                .getTypesAnnotatedWith(Decorator.class)
                .forEach(decoratorInterfaceImpl -> {
                    Class<?> decoratorInterface = decoratorInterfaceImpl.getInterfaces()[0];
                    MAPPING.put(decoratorInterface, decoratorInterfaceImpl);
                    Type type = decoratorInterfaceImpl.getGenericSuperclass();
                    if (type instanceof ParameterizedType) {
                        ParameterizedType parameterizedType = (ParameterizedType) type;
                        // 获取泛型参数
                        Class<?> targetInterface = (Class<?>) parameterizedType.getActualTypeArguments()[0];
                        MAPPING.put(decoratorInterfaceImpl, targetInterface);
                    }
                });
    }


    public Class<?> getTargetInterface(Class<?> key) {
        if (Modifier.isInterface(key.getModifiers())) {
            key = MAPPING.get(key);
        }
        return MAPPING.get(key);
    }

    public Class<?> getDecoratorInterfaceImpl(Class<?> key) {
        return MAPPING.get(key);
    }
}
